class ServiceRescueController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, ngDialog, dialogService, ServiceService, getCourseList, iRunner, getRaceDetail){

        var vm = this;

        vm.$rootScope     = $rootScope;
        vm.$cookieStore   = $cookieStore;
        vm.$timeout       = $timeout;
        vm.$state         = $state;
        vm.ngDialog       = ngDialog;
        vm.dialogService  = dialogService;
        vm.ServiceService = ServiceService;
        vm.getCourseList  = getCourseList;
        vm.iRunner        = iRunner;
        vm.getRaceDetail  = getRaceDetail;

        //路径颜色List
        vm.pathColor = [
            {"color": "#FF0000", "R":255, "G":0, "B":0},
            {"color": "#0000FF", "R":0, "G":0, "B":255},
            {"color": "#FF00FF", "R":255, "G":0, "B":255},
            {"color": "#018904", "R":1, "G":137, "B":4},
            {"color": "#707070", "R":112, "G":112, "B":112},
            {"color": "#FF7800", "R":255, "G":120, "B":0}
        ];

        //用于存储路线List
        vm.polylineList = [];

        //文本标记List
        vm.mackList = [];

        //刷新按钮flag
        vm.refreshFlag = false;

        //定时器
        vm.timeout = 10000;

        //默认没有选择科目（添加checked属性）
        vm.getCourseList.data.forEach(function(element, index) {
           element.checked = false;
        });

        console.log(vm.getCourseList.data);

        /**
         * [checkCrouse 选择科目]
         * @param  {[type]} id [description]
         * @return {[type]}    [description]
         */
        vm.checkCrouse = function(id) {

            //刷新请求的场合
            if (!id) {
                id = vm.currentCrouseId;
            }

            //存储当前科目id （用于定时刷新）
            vm.currentCrouseId = id;

            //改变科目按钮显示状态
            vm.getCourseList.data.forEach(function(element, index) {
                if (element.course_id == id) {
                   element.checked = true;
                } else {
                   element.checked = false;
                }
            });

            //请求该科目数据接口
            vm.ServiceService.getServiceTraceLists(vm.$cookieStore.get('access_token'), id)
            .then(function(data) {
                console.log(data.data);
                // 成功调用
                if (data.code==0) {
                    vm.cpInfoList = data.data;

                    vm.cpInfoList.forEach(function(element, index) {
                        if (element.parcent < 30) {
                            element.state = 'danger';
                        } else if (element.parcent >= 30 && element.parcent < 70) {
                            element.state = 'warning';
                        } else  if (element.parcent >= 70) {
                            element.state = 'info';
                        }
                    });

                }
                // 调用失败, 提示用户
                (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);
                // 登录信息已过期, 请重新登录
                data.code==-1001&&vm.dialogService.error(data.message, true);
            }, function(data) {
                console.log('error')
            });

        }
        
        //初始化选择第一个科目
        vm.checkCrouse(vm.getCourseList.data[0].course_id);

        /**
         * [refreshChange 切换选手动态刷新状态]
         * @param  {[type]} value [刷新状态flag]
         * @return {[type]}       [description]
         */
        vm.refreshChange = function() {
            // 切换按钮显示
            vm.refreshFlag = !vm.refreshFlag
            //改变按钮显示状态
            if (vm.refreshFlag) {
                clearInterval(vm.timer);
            } else {
                vm.timer = setInterval(vm.checkCrouse, vm.timeout);
            }
        };


        //定时刷新青请求科目通过率及人数
        vm.timer = setInterval(vm.checkCrouse, vm.timeout);

        /**
         * [srarch 搜索某个选手]
         * @param  {[type]} bib [description]
         * @return {[type]}     [description]
         */
        vm.search = function(bib) {

            if (!bib) {
                vm.dialogService.error("请输入要查询的选手号！");
                return;
            }
            // 调用接口获取选手详情
            vm.ServiceService.postServiceTraceSearchRunner({ bib: bib}, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
            .then(function(data) {
                console.log(data);
                // 成功调用
                if (data.code==0 && data.data.runner) {
                    //查询到选手的场合
                    vm.runnerInfo = data.data;
                    //显示选手动态
                    vm.runnerInfoFlag = true;
                } else if (data.code==0 && !data.data.runner) {
                    vm.dialogService.error('没有查询到该选手');
                    return;
                }
                // 调用失败, 提示用户
                (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);
                // 登录信息已过期, 请重新登录
                data.code==-1001&&vm.dialogService.error(data.message, true);
            }, function(data) {
                console.log('error')
            });
        }

        /**
         * [success 获取地图数据json]
         */
        $.ajax({
            type: "post",
            dataType: "json",
            url: "/mapJson/" + vm.$state.params.race_id + ".json",
            success: function (data) {
                //成功取到地图数据的场合
                //路线list
                vm.json = data.pathList;
                //cp点信息list
                vm.cpList = data.cpList;
                //地图尺寸
                vm.mapSize = parseInt(data.mapSize);
                //创建地图
                vm.greatMap(vm.json, vm.mapSize);
            },
            error: function () {
                //没有取到地图的情况下
                //进行地址解析，创建地图
                vm.geocoder = new qq.maps.Geocoder({
                    complete : function(result){
                    vm.map = new qq.maps.Map(document.getElementById('map'),{
                        center: result.detail.location,
                        zoom: 11
                    });
                    }
                });

                vm.geocoder.getLocation(vm.getRaceDetail.data.province ? vm.getRaceDetail.data.province : '上海市');
                console.log(vm.getRaceDetail.data.province);
            }
        });

        /**
         * [greatMap 创建路线图]
         * @param  {[type]} json    [路线list]
         * @param  {[type]} mapSize [地图尺寸]
         * @return {[type]}         [description]
         */
        vm.greatMap = function(json, mapSize) {

            //数据已经加工好（排序完成的路径）
            vm.pathOrder = getPathList2(json);
            console.log(vm.pathOrder);
            //最长的路径
            var pathMax = vm.pathOrder[vm.pathOrder.length -1].path;
            //地图初始中心点
            vm.center = setMapCenter(pathMax);

             //创建地图
            //定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
            vm.map = new qq.maps.Map(document.getElementById("map"), {
                // 地图的中心地理坐标。
                center: vm.center,
                // 地图的中心地理坐标。
                zoom: mapSize + 1,
            });

            //路线显示样式
            vm.pathOrder.forEach(function(element, index) {
                // console.log(element.id);
                vm.polyline = {
                    id: element.id,
                    polyline: {}
                };
                vm.polylineList.push(vm.polyline);

                //不进行纠偏
                vm.polylineList[index].polyline = new qq.maps.Polyline({
                    path: element.path,
                    strokeColor: new qq.maps.Color(vm.pathColor[index].R, vm.pathColor[index].G, vm.pathColor[index].B, 1),
                    strokeWeight: 3,
                    zIndex: vm.pathOrder.length - index,
                    editable:false,
                    map: vm.map
                });

            });
            //显示cp点信息
            vm.setCpMark();
        };

        /**
         * [setCpMark 添加cp信息]
         */
        vm.setCpMark = function() {

            var cssC = {
                color: "#FFFFFF",
                fontSize: "12px",
                backgroundColor: "#ADADAD",
                border: "0px",
                padding: "4px",
                opacity: "0.7",
                borderRadius: "5px",
            };

            vm.cpList.forEach(function(element, index) {
                
                //显示标记
                var label = new qq.maps.Label({
                    position: new qq.maps.LatLng(element.cpPoint.lat, element.cpPoint.lng),
                    animation: qq.maps.MarkerAnimation.DROP,
                    map: vm.map,
                    style: cssC,
                    content: element.cpName,
                    offset: new qq.maps.Size(-18, -45)
                });

                //显示icon
                var icon = new qq.maps.Marker({
                    position: new qq.maps.LatLng(element.cpPoint.lat, element.cpPoint.lng),
                    animation: qq.maps.MarkerAnimation.DROP,
                    icon: new qq.maps.MarkerImage("/img/live/mark.png"),
                    map: vm.map,
                    visible: true
                });

                var mark = {
                    "lable": label,
                    "icon": icon,
                    "cpId": element.cpId,
                    "cpName": element.cpName
                };

                vm.mackList.push(mark);
            });
        };

        /**
         * [getPathList2 生成路径]
         * @param  {[type]} json [json]
         * @return {[type]}      [description]
         */
        function getPathList2(json) {
            var pathList = [];
            json.forEach(function(element, index) {
                var path = [];
                //路线生成
                for (var i = 0; i < element.path.length; i++) {
                    var lat = element.path[i].lat;
                    var lng = element.path[i].lng;
                    var point = new qq.maps.LatLng(lat, lng);
                    path.push(point);
                }
                var pathInfo = {
                    "name": element.name,
                    "id": element.id,
                    "distance": element.distance,
                    "path": path
                };
                //加入到路线List
                pathList.push(pathInfo);
            });
            return pathList;
        }

        /**
         * [setMapCenter 计算地图中心点]
         * @param {[type]} pathMax [路线]
         */
        function setMapCenter(pathMax) {
            //路线的长度
            var length = pathMax.length;
            //取样10个
            var point1 = pathMax[parseInt(length/10)];
            var point2 = pathMax[parseInt(length/10*2)];
            var point3 = pathMax[parseInt(length/10*3)];
            var point4 = pathMax[parseInt(length/10*4)];
            var point5 = pathMax[parseInt(length/10*5)];
            var point6 = pathMax[parseInt(length/10*6)];
            var point7 = pathMax[parseInt(length/10*7)];
            var point8 = pathMax[parseInt(length/10*8)];
            var point9 = pathMax[parseInt(length/10*9)];
            var point0 = pathMax[length-1];
            //取10个采样的中心点
            var center = new qq.maps.LatLng((point1.lat+point2.lat+point3.lat+point4.lat+point5.lat+point6.lat+point7.lat+point8.lat+point9.lat+point0.lat)/10, (point1.lng+point2.lng+point3.lng+point4.lng+point5.lng+point6.lng+point7.lng+point8.lng+point9.lng+point0.lng)/10);
            return center;
        }

    }
}

ServiceRescueController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', 'ngDialog', 'dialogService', 'ServiceService', 'getCourseList', 'iRunner', 'getRaceDetail']; 

export default ServiceRescueController;